#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : test06_system_management.py
@Time : 2025/2/7 14:16
@Author: Wangwc
@Describe:  ……
"""
import datetime
import random
import time
import warnings

warnings.filterwarnings("ignore", category=DeprecationWarning)
from urllib3.exceptions import InsecureRequestWarning

warnings.simplefilter('ignore', category=InsecureRequestWarning)
import allure
import pytest

from business.SystemApi import SystemApi
from utils.login import Login
from commons.logger import log
from utils.config_tools import Config
from commons.fake_data import Fake

# TODO 当前模块的配置文件名称，配置在config目录下
config_name = "user.ini"
login = Login(config_name=config_name)
config = Config(config_name=config_name)

global_token = None

@pytest.fixture(scope="function")
def system_api():
    global global_token
    if global_token is None:
        global_token = login.login()
    api = SystemApi(global_token, configname=config_name)
    return api


def handle_api_call(api_method, *args, attach_to_allure=True, format_result=None, **kwargs):
    if not callable(api_method):
        raise TypeError("api_method 参数必须是可调用对象（如函数或方法）")
    if attach_to_allure is not None and not isinstance(attach_to_allure, bool):
        raise TypeError("attach_to_allure 参数必须是布尔类型或者为 None")
    if format_result is not None and not callable(format_result):
        raise TypeError("format_result 参数必须是可调用对象（如函数）或者为 None")

    max_retries = 3
    for retry in range(max_retries):
        try:
            result = api_method(*args, **kwargs)
            if attach_to_allure:
                if format_result:
                    formatted_result = format_result(result)
                else:
                    formatted_result = str(result)
                allure.attach(formatted_result, f"{api_method.__name__} 调用结果", allure.attachment_type.TEXT)
            log.info(f"{api_method.__name__} 调用成功")
            return result
        except Exception as e:
            allure.attach(str(e), f"{api_method.__name__} 调用错误信息", allure.attachment_type.TEXT)
            log.error(f"{api_method.__name__} 调用出现错误: {e}", exc_info=True)
            # 假设根据错误信息判断 token 过期
            if "token 过期" in str(e) and retry < max_retries - 1:
                global global_token
                global_token = login.login()
                api_method.__self__.token = global_token
                continue
            elif isinstance(e, ConnectionError):
                log.error("连接错误，可能是网络问题，请检查网络连接。")
            elif isinstance(e, ValueError):
                log.error("值错误，可能是传入的参数有误，请检查参数。")
            raise

@allure.feature("控制面板-系统管理")
class TestSystemManagement():
    @allure.title("开启FTP功能后可以正常登录")
    def test_start_ftp(self, system_api):
        with allure.step("开启FTP"):
            handle_api_call(system_api.start_ftp, enable_ftp=True)

        with allure.step("确认FTP已开启"):
            results = handle_api_call(system_api.get_ftp_config)
            ftp_port = results.get('port')
            assert results.get("enable_ftp") == True

        with allure.step("使用FTP登录"):
            host = config.read_config_ini('envHost', 'hostname')
            username = config.read_config_ini('user', 'user_name')
            password = config.read_config_ini('user', 'user_pwd')
            result = handle_api_call(system_api.check_ftp_service, host, port=ftp_port, username=username,
                                     password=password)
            assert result == True

    @allure.title("关闭FTP功能后不能登录")
    def test_stop_ftp(self, system_api):
        with allure.step("开启FTP"):
            handle_api_call(system_api.start_ftp, enable_ftp=True)

        with allure.step("确认FTP已开启"):
            results = handle_api_call(system_api.get_ftp_config)
            ftp_port = results.get('port')
            assert results.get("enable_ftp") == True

        with allure.step("关闭FTPS"):
            handle_api_call(system_api.stop_ftp)
            new_results = handle_api_call(system_api.get_ftp_config)
            assert new_results.get("enable_ftp") == False
            assert new_results.get("enable_ftps") == False

        with allure.step("使用FTP登录"):
            host = config.read_config_ini('envHost', 'hostname')
            username = config.read_config_ini('user', 'user_name')
            password = config.read_config_ini('user', 'user_pwd')
            result = handle_api_call(system_api.check_ftp_service, host, port=ftp_port, username=username,
                                     password=password)
            assert result == False

    @allure.title("开启FTPS功能后可以正常登录")
    def test_start_ftps(self, system_api):
        with allure.step("开启FTPS"):
            handle_api_call(system_api.start_ftp, enable_ftps=True)

        with allure.step("确认FTPS已开启"):
            results = handle_api_call(system_api.get_ftp_config)
            ftp_port = results.get('port')
            assert results.get("enable_ftps") == True

        with allure.step("使用FTPS登录"):
            host = config.read_config_ini('envHost', 'hostname')
            username = config.read_config_ini('user', 'user_name')
            password = config.read_config_ini('user', 'user_pwd')
            result = handle_api_call(system_api.check_ftps_service, host, port=ftp_port, username=username,
                                     password=password)
            assert result == True

    @allure.title("关闭FTPS功能后不能登录")
    def test_stop_ftps(self, system_api):
        with allure.step("开启FTPS"):
            handle_api_call(system_api.start_ftp, enable_ftps=True)

        with allure.step("确认FTPS已开启"):
            results = handle_api_call(system_api.get_ftp_config)
            ftp_port = results.get('port')
            assert results.get("enable_ftps") == True

        with allure.step("关闭FTPS"):
            handle_api_call(system_api.stop_ftp)
            new_results = handle_api_call(system_api.get_ftp_config)
            assert new_results.get("enable_ftp") == False
            assert new_results.get("enable_ftps") == False

        with allure.step("使用FTPS登录"):
            host = config.read_config_ini('envHost', 'hostname')
            username = config.read_config_ini('user', 'user_name')
            password = config.read_config_ini('user', 'user_pwd')
            result = handle_api_call(system_api.check_ftps_service, host, port=ftp_port, username=username,
                                     password=password)
            assert result == False

    @allure.title("FTPS自定义端口后可以正常登录")
    def test_set_ftps_port(self, system_api):
        with allure.step("开启FTPS"):
            set_port = random.randint(10000, 20000)
            handle_api_call(system_api.start_ftp, enable_ftps=True, port=set_port)

        with allure.step("确认FTPS已开启"):
            results = handle_api_call(system_api.get_ftp_config)
            ftps_port = results.get('port')
            assert results.get("enable_ftps") == True
            assert ftps_port == set_port

        with allure.step("使用FTPS登录"):
            host = config.read_config_ini('envHost', 'hostname')
            username = config.read_config_ini('user', 'user_name')
            password = config.read_config_ini('user', 'user_pwd')
            result = handle_api_call(system_api.check_ftps_service, host, port=ftps_port, username=username,
                                     password=password)
            assert result == True

    @allure.title("Telnet自定义端口后可以正常登录")
    def test_set_telnet_port(self, system_api):
        with allure.step("开启telnet"):
            set_port = random.randint(20000, 30000)
            handle_api_call(system_api.set_terminal, telnet_enable=1, telnet_port=set_port)

        with allure.step("确认telnet已开启"):
            results = handle_api_call(system_api.get_terminal)
            telnet_port = results.get('TelnetConfig').get('port')
            telnet_enable = results.get('TelnetConfig').get('enable')
            assert telnet_enable == 1
            assert telnet_port == set_port

        with allure.step("使用telnet登录"):
            host = config.read_config_ini('envHost', 'hostname')
            username = config.read_config_ini('user', 'user_name')
            password = config.read_config_ini('user', 'user_pwd')
            result = handle_api_call(system_api.telnet_login, host, port=telnet_port, username=username,
                                     password=password)
            assert result == True

    @allure.title("获取本地备份文件流")
    def test_get_backup_restore(self, system_api):
        with allure.step("获取用户uid"):
            username = config.read_config_ini('user', 'user_name')
            uid = handle_api_call(system_api.get_user_uid, username)

        with allure.step("获取本地备份文件流"):
            results = handle_api_call(system_api.backup_restore, uid)
            assert results.content != None

    @allure.title("获取本机常规信息")
    def test_get_machine_common(self, system_api):
        with allure.step("读取配置文件本机信息"):
            device_model = config.read_config_ini('device', 'device_model')
            device_sn = config.read_config_ini('device', 'device_sn')

        with allure.step("获取本机常规信息"):
            results = handle_api_call(system_api.get_machine_common)
            assert results.get('common').get(
                'model') == device_model, f"获取本机常规信息失败，预期：{device_model}，实际：{results.get('common').get('model')}"
            assert results.get('common').get(
                'serial') == device_sn, f"获取本机常规信息失败，预期：{device_sn}，实际：{results.get('common').get('serial')}"

    @allure.title("获取关于本机存储&服务信息")
    def test_get_storage_and_collect(self, system_api):
        with allure.step("获取本机存储信息"):
            results = handle_api_call(system_api.get_storage_info)
            assert results.get('disks') != None
            assert results.get('pools') != None
            assert results.get('volumes') != None

        with allure.step("获取本机服务信息"):
            results_list = handle_api_call(system_api.get_sysinfo_collect)
            ports_list = [i.get('ports') for i in results_list]
            assert '22' in ports_list

    @allure.title("修改主机名称")
    def test_change_hostname(self, system_api):
        with allure.step("获取主机名称"):
            results = handle_api_call(system_api.get_machine_common)
            hostname = results.get('common').get('nas_name')
            device_name = config.read_config_ini('device', 'device_name')
            assert hostname == device_name, f"获取主机名称失败，预期：{device_name}，实际：{hostname}"

        with allure.step("修改主机名称"):
            device_model = config.read_config_ini('device', 'device_model')
            fake_name = Fake.generate_english_username()
            set_hostname = f"{device_model}-{fake_name}"
            handle_api_call(system_api.change_machine_hostname, set_hostname)

        with allure.step("再次获取主机名称"):
            new_results = handle_api_call(system_api.get_machine_common)
            new_hostname = new_results.get('common').get('nas_name')
            assert new_hostname == set_hostname, f"修改主机名称失败，预期：{set_hostname}，实际：{new_hostname}"

        with allure.step("恢复主机名称"):
            handle_api_call(system_api.change_machine_hostname, device_name)
            time.sleep(1)
            final_results = handle_api_call(system_api.get_machine_common)
            final_hostname = final_results.get('common').get('nas_name')
            assert final_hostname == device_name, f"恢复主机名称失败，预期：{device_name}，实际：{final_hostname}"

    @allure.title("设备分析")
    def test_device_analyze(self, system_api):
        with allure.step("获取设备分析息"):
            results = handle_api_call(system_api.get_finder_info)
            improvement_enable = results.get('improvement_enable')
            web_find = results.get('web_find')

        with allure.step("更改设备分析"):
            set_improvement_enable = 0 if improvement_enable == 1 else 1
            set_web_find = 0 if web_find == 1 else 1
            handle_api_call(system_api.set_finder_info, set_improvement_enable, set_web_find)

        with allure.step("再次获取设备分析息"):
            new_results = handle_api_call(system_api.get_finder_info)
            new_improvement_enable = new_results.get('improvement_enable')
            new_web_find = new_results.get('web_find')
            assert new_improvement_enable == set_improvement_enable, f"更改设备分析失败，预期：{set_improvement_enable}，实际：{new_improvement_enable}"
            assert new_web_find == set_web_find, f"更改设备分析失败，预期：{set_web_find}，实际：{new_web_find}"

    @allure.title("获取保修时间")
    def test_machine_repair(self, system_api):
        with allure.step("读取配置信息保修天数"):
            repair_days = config.read_config_ini('device', 'repair_days')

        with allure.step("获取保修时间"):
            results = handle_api_call(system_api.get_machine_repair_info)
            start_time = results.get('repairStartTime')
            end_time = results.get('repairEndTime')
            days = (end_time - start_time) / (24 * 60 * 60 * 1000)
            assert days == int(repair_days), f"获取保修时间失败，预期：{repair_days}，实际：{days}"

    @allure.title("重建索引")
    def test_rebuild_index(self, system_api):
        with allure.step("获取索引信息"):
            results = handle_api_call(system_api.get_index_info)
            index_status = results.get('idxInfo').get('status')

        with allure.step("重建索引"):
            handle_api_call(system_api.rebuild_index)

        with allure.step("获取索引详细信息"):
            index_details = handle_api_call(system_api.get_index_detail)
            assert index_details.get('idxInfo').get(
                'status') == 1, f"重建索引失败，预期：1，实际：{index_details.get('idxInfo').get('status')}"

        with allure.step("等待索引信息完成"):
            if handle_api_call(system_api.check_index_status):
                new_results = handle_api_call(system_api.get_index_info)
                assert new_results.get('idxInfo').get(
                    'status') == index_status, f"重建索引失败，预期：{index_status}，实际：{new_results.get('idxInfo').get('status')}"

    @allure.title("重建缩略图")
    def test_rebuild_thumb(self, system_api):
        with allure.step("获取索引信息"):
            results = handle_api_call(system_api.get_index_info)
            thumb_status = results.get('thumbInfo').get('status')

        with allure.step("重建缩略图"):
            handle_api_call(system_api.rebuild_thumb)

        with allure.step("获取索引详细信息"):
            thumb_details = handle_api_call(system_api.get_index_detail)
            assert thumb_details.get('thumbInfo').get(
                'status') == 1, f"重建索引失败，预期：1，实际：{thumb_details.get('thumbInfo').get('status')}"

        with allure.step("等待索引信息完成"):
            if handle_api_call(system_api.check_index_status, index='thumbInfo'):
                new_results = handle_api_call(system_api.get_index_info)
                assert new_results.get('thumbInfo').get(
                    'status') == thumb_status, f"重建缩略图失败，预期：{thumb_status}，实际：{new_results.get('thumbInfo').get('status')}"

    @allure.title("更改缩略图高级设置")
    def test_change_thumb(self, system_api):
        with allure.step("获取缩略图高级设置"):
            results = handle_api_call(system_api.get_thumb_set)
            picQuality = results.get('picQuality')
            videoQuality = results.get('videoQuality')

        with allure.step("更改缩略图高级设置"):
            set_pic = 3 if picQuality == 1 else 1
            set_video = 3 if videoQuality == 1 else 1
            handle_api_call(system_api.set_thumb_set, picQuality=set_pic, videoQuality=set_video)

        with allure.step("重新获取缩略图高级设置"):
            new_results = handle_api_call(system_api.get_thumb_set)
            new_picQuality = new_results.get('picQuality')
            new_videoQuality = new_results.get('videoQuality')
            assert new_picQuality == set_pic, f"更改缩略图高级设置失败，预期：{set_pic}，实际：{new_picQuality}"
            assert new_videoQuality == set_video, f"更改缩略图高级设置失败，预期：{set_video}，实际：{new_videoQuality}"

    @allure.title("更改蜂鸣器设置")
    def test_change_buzzer(self, system_api):
        with allure.step("获取蜂鸣器设置"):
            results = handle_api_call(system_api.get_buzzer_config)
            assert results is not None, "获取蜂鸣器设置失败"

        with allure.step("更改蜂鸣器设置"):
            set_fan_fault = random.randint(0, 1)
            set_cache_exception = random.randint(0, 1)
            set_system_startup = random.randint(0, 1)
            set_system_shutdown = random.randint(0, 1)
            set_temperature = random.randint(0, 1)
            handle_api_call(system_api.set_buzzer_config, fan_fault=set_fan_fault, cache_exception=set_cache_exception,
                            system_startup=set_system_startup, system_shutdown=set_system_shutdown,
                            temperature_too_high=set_temperature)

        with allure.step("重新获取蜂鸣器设置"):
            new_results = handle_api_call(system_api.get_buzzer_config)
            new_fan_fault = new_results.get('fan_fault')
            new_cache_exception = new_results.get('cache_exception')
            new_system_startup = new_results.get('system_startup')
            new_system_shutdown = new_results.get('system_shutdown')
            new_temperature = new_results.get('temperature_too_high')
            assert new_fan_fault == set_fan_fault, f"更改蜂鸣器设置失败，预期：{set_fan_fault}，实际：{new_fan_fault}"
            assert new_cache_exception == set_cache_exception, f"更改蜂鸣器设置失败，预期：{set_cache_exception}，实际：{new_cache_exception}"
            assert new_system_startup == set_system_startup, f"更改蜂鸣器设置失败，预期：{set_system_startup}，实际：{new_system_startup}"
            assert new_system_shutdown == set_system_shutdown, f"更改蜂鸣器设置失败，预期：{set_system_shutdown}，实际：{new_system_shutdown}"
            assert new_temperature == set_temperature, f"更改蜂鸣器设置失败，预期：{set_temperature}，实际：{new_temperature}"

    @allure.title("更改冷却风扇设置")
    def test_change_fan(self, system_api):
        with allure.step("获取冷却风扇设置"):
            mode = handle_api_call(system_api.get_fan_config)
            assert mode is not None, "获取冷却风扇设置失败"

        with allure.step("更改冷却风扇设置"):
            set_mode = random.randint(1, 3)
            handle_api_call(system_api.set_fan_config, mode=set_mode)

        with allure.step("重新获取冷却风扇设置"):
            new_mode = handle_api_call(system_api.get_fan_config)
            assert new_mode == set_mode, f"更改冷却风扇设置失败，预期：{set_mode}，实际：{new_mode}"

    @allure.title("更改LED指示灯设置")
    def test_change_led(self, system_api):
        with allure.step("获取LED指示灯设置"):
            led_info = handle_api_call(system_api.get_led_config)
            assert led_info is not None, "获取LED指示灯设置失败"

        with allure.step("更改LED指示灯设置"):
            days_elements = [1, 2, 3, 4, 5, 6, 7]
            days_num = random.randint(1, 7)
            days_list = random.sample(days_elements, days_num)
            time_elements = [i for i in range(24)]
            # 随机确定列表元素的个数，范围是 1 到 24
            time_num = random.randint(1, 24)
            # 随机选择起始位置
            start_index = random.randint(0, 24 - time_num)
            # 截取连续的元素
            time_list = time_elements[start_index:start_index + time_num]
            bright = random.randint(0, 100)
            handle_api_call(system_api.set_led_config, days_list, time_list, bright)

        with allure.step("重新获取LED指示灯设置"):
            new_led_info = handle_api_call(system_api.get_led_config)
            timeConfig = new_led_info[0].get('timeConfig')
            assert new_led_info[0].get(
                'days') == days_list, f"更改LED指示灯设置失败，预期：{days_list}，实际：{new_led_info[0].get('days')}"
            assert timeConfig[0].get('time') == time_list, f"更改LED指示灯设置失败，预期：{time_list}，实际：{timeConfig[0].get('time')}"
            assert timeConfig[0].get('bright') == bright, f"更改LED指示灯设置失败，预期：{bright}，实际：{timeConfig[0].get('bright')}"

    @allure.title("更改电源设置")
    def test_change_power(self, system_api):
        with allure.step("获取电源设置"):
            frequency = handle_api_call(system_api.get_cpu_config)
            assert frequency is not None, "获取电源设置失败"

        with allure.step("更改电源设置"):
            set_frequency = random.randint(0, 2)
            handle_api_call(system_api.set_cpu_config, set_frequency)

        with allure.step("重新获取电源设置"):
            new_frequency = handle_api_call(system_api.get_cpu_config)
            assert new_frequency == set_frequency, f"更改电源设置失败，预期：{set_frequency}，实际：{new_frequency}"

    @allure.title("开关机设置")
    def test_power_boot(self, system_api):
        with allure.step("获取开关机设置"):
            results = handle_api_call(system_api.get_power_config)
            log.debug(f"开始获取到的开关机设置结果为：{results}")

        with allure.step("更改开关机设置"):
            set_power_boot = random.choice([True, False])
            set_wake_on = random.choice([True, False])
            handle_api_call(system_api.set_power_config, power_boot=set_power_boot, wake_on=set_wake_on)

        with allure.step("再次获取开关机设置"):
            new_results = handle_api_call(system_api.get_power_config)
            new_power_boot = new_results.get('power_boot')
            new_wake_on = new_results.get('wake_on')
            assert new_power_boot == set_power_boot, f"更改开关机设置失败，预期：{set_power_boot}，实际：{new_power_boot}"
            assert new_wake_on == set_wake_on, f"更改开关机设置失败，预期：{set_wake_on}，实际：{new_wake_on}"

    @allure.title("定时开机")
    def test_power_on(self, system_api):
        with allure.step("新增定时开机"):
            days_elements = [1, 2, 3, 4, 5, 6, 7]
            days_num = random.randint(1, 7)
            days_list = random.sample(days_elements, days_num)
            time = (datetime.datetime.now() + datetime.timedelta(hours=random.randint(5, 10))).strftime("%H:%M")
            set_switches = [{'frequency': days_list, 'time': time, 'action': 'open'}]
            handle_api_call(system_api.set_power_config, time_switches=set_switches)

        with allure.step("获取开关机设置"):
            results = handle_api_call(system_api.get_power_config)
            time_switches = results.get('time_switches')
            assert set_switches == time_switches, f"新增开机设置失败，预期包含{set_switches}，实际：{time_switches}"

        with allure.step("删除定时开机"):
            handle_api_call(system_api.set_power_config)

        with allure.step("再次获取开关机设置"):
            new_results = handle_api_call(system_api.get_power_config)
            new_time_switches = new_results.get('time_switches')
            assert new_time_switches == [], f"删除开机设置失败，预期：[]，实际：{new_time_switches}"

    @allure.title("定时关机")
    def test_power_off(self, system_api):
        with allure.step("新增定时关机"):
            days_elements = [1, 2, 3, 4, 5, 6, 7]
            days_num = random.randint(1, 7)
            days_list = random.sample(days_elements, days_num)
            time = (datetime.datetime.now() + datetime.timedelta(hours=random.randint(5, 10))).strftime("%H:%M")
            set_switches = [{'frequency': days_list, 'time': time, 'action': 'close'}]
            handle_api_call(system_api.set_power_config, time_switches=set_switches)

        with allure.step("获取开关机设置"):
            results = handle_api_call(system_api.get_power_config)
            time_switches = results.get('time_switches')
            assert set_switches == time_switches, f"新增关机设置失败，预期包含{set_switches}，实际：{time_switches}"

        with allure.step("删除定时关机"):
            handle_api_call(system_api.set_power_config)

        with allure.step("再次获取开关机设置"):
            new_results = handle_api_call(system_api.get_power_config)
            new_time_switches = new_results.get('time_switches')
            assert new_time_switches == [], f"删除开机设置失败，预期：[]，实际：{new_time_switches}"

    @allure.title("硬盘休眠")
    def test_hard_drive(self, system_api):
        with allure.step("设置硬盘休眠"):
            hard_drive_flag = random.choice([True, False])
            enable_hard_drive_sleep_log = random.choice([True, False]) if hard_drive_flag == True else False
            hard_drive_unit = random.choice(["M", "H"])
            hard_drive_time = random.choice([10, 20, 30]) if hard_drive_unit == "M" else random.randint(1, 3)
            handle_api_call(system_api.set_power_config, hard_drive_flag=hard_drive_flag,
                            enable_hard_drive_sleep_log=enable_hard_drive_sleep_log, hard_drive_unit=hard_drive_unit,
                            hard_drive_time=hard_drive_time)

        with allure.step("确认设置硬盘休眠成功"):
            results = handle_api_call(system_api.get_power_config)
            new_hard_drive_flag = results.get('hard_drive_flag')
            new_enable_hard_drive_sleep_log = results.get('enable_hard_drive_sleep_log')
            new_hard_drive_unit = results.get('hard_drive_unit')
            new_hard_drive_time = results.get('hard_drive_time')
            assert new_hard_drive_flag == hard_drive_flag, f"设置硬盘休眠失败，预期：{hard_drive_flag}，实际：{new_hard_drive_flag}"
            assert new_enable_hard_drive_sleep_log == enable_hard_drive_sleep_log, f"设置硬盘休眠失败，预期：{enable_hard_drive_sleep_log}，实际：{new_enable_hard_drive_sleep_log}"
            assert new_hard_drive_unit == hard_drive_unit, f"设置硬盘休眠失败，预期：{hard_drive_unit}，实际：{new_hard_drive_unit}"
            assert new_hard_drive_time == hard_drive_time, f"设置硬盘休眠失败，预期：{hard_drive_time}，实际：{new_hard_drive_time}"

    @allure.title("USB硬盘休眠")
    def test_usb_hard_drive(self, system_api):
        with allure.step("设置USB硬盘休眠"):
            usb_hard_drive_flag = random.choice([True, False])
            usb_hard_drive_unit = random.choice(["M", "H"])
            usb_hard_drive_time = random.choice([10, 20, 30]) if usb_hard_drive_unit == "M" else random.randint(1, 3)
            handle_api_call(system_api.set_power_config, usb_hard_drive_flag=usb_hard_drive_flag,
                            usb_hard_drive_unit=usb_hard_drive_unit, usb_hard_drive_time=usb_hard_drive_time)

        with allure.step("确认设置USB硬盘休眠成功"):
            results = handle_api_call(system_api.get_power_config)
            new_usb_hard_drive_flag = results.get('usb_hard_drive_flag')
            new_usb_hard_drive_unit = results.get('usb_hard_drive_unit')
            new_usb_hard_drive_time = results.get('usb_hard_drive_time')
            assert new_usb_hard_drive_flag == usb_hard_drive_flag, f"设置硬盘休眠失败，预期：{usb_hard_drive_flag}，实际：{new_usb_hard_drive_flag}"
            assert new_usb_hard_drive_unit == usb_hard_drive_unit, f"设置硬盘休眠失败，预期：{usb_hard_drive_unit}，实际：{new_usb_hard_drive_unit}"
            assert new_usb_hard_drive_time == usb_hard_drive_time, f"设置硬盘休眠失败，预期：{usb_hard_drive_time}，实际：{new_usb_hard_drive_time}"

    @allure.title("更改系统时间")
    def test_change_time(self, system_api):
        with allure.step("获取系统时间"):
            results = handle_api_call(system_api.get_time_config)
            time_set_type = results.get('time_set_type')

        with allure.step("手动设置系统时间"):
            time = random.randint(1740009600, 1740095999)
            date_format = results.get('date_format')
            time_format = results.get('time_format')
            time_server = results.get('time_server')
            time_zone = results.get('time_zone')
            time_show = datetime.datetime.utcfromtimestamp(time).strftime("%Y-%m-%d %H:%M:%S")
            handle_api_call(system_api.set_time_by_hand, time)
            handle_api_call(system_api.set_global_time_config, time_show=time_show, time_zone=time_zone,
                            time_set_type=1,
                            time=time, time_server=time_server, date_format=date_format, time_format=time_format)

        with allure.step("再次获取系统时间"):
            new_results = handle_api_call(system_api.get_time_config)
            new_time_show = new_results.get('time_show')
            new_time_set_type = new_results.get('time_set_type')
            assert new_time_set_type != time_set_type, f"设置系统时间失败，预期：手动，实际：{new_time_set_type}"
            assert '2025-02-20' in new_time_show, f"设置系统时间失败，预期时间包含：2025-02-20，实际时间：{new_time_show}"

        with allure.step("恢复自动与时间服务器同步"):
            date1 = time_show.split(' ')[0]
            log.info(f"data1的值为：{date1}")
            time1 = time_show.split(' ')[1]
            log.info(f"time1的值为：{time1}")
            handle_api_call(system_api.set_global_time_config, time_zone=time_zone, time_set_type=0,
                            time_server=time_server, date_format=date_format, time_format=time_format, date1=date1,
                            time1=time1)

    @allure.title("更改系统时间服务器")
    def test_change_time_server(self, system_api):
        with allure.step("获取系统时间服务器"):
            server_list = handle_api_call(system_api.get_time_server)

        with allure.step("添加系统时间服务器"):
            add_time_server = random.choice(['ntp.aliyun.com','ntp.tencent.com', 'cn.pool.ntp.org'])
            handle_api_call(system_api.add_time_server, add_time_server)

        with allure.step("确认成功添加时间服务器"):
            new_server_list = handle_api_call(system_api.get_time_server)
            assert len(new_server_list) == len(
                server_list) + 1, f"添加时间服务器失败，预期：{len(server_list) + 1}，实际：{len(new_server_list)}"

        with allure.step("删除系统时间服务器"):
            filtered_list = [server for server in new_server_list if server != 'pool.ntp.org']
            if filtered_list:
                del_time_server = random.choice(filtered_list)
                handle_api_call(system_api.del_time_server, del_time_server)

        with allure.step("确认成功添加时间服务器"):
            final_server_list = handle_api_call(system_api.get_time_server)
            assert len(final_server_list) == len(
                new_server_list) - 1, f"添加时间服务器失败，预期：{len(new_server_list) - 1}，实际：{len(final_server_list)}"

    @allure.title("更改系统语言")
    def test_change_language(self, system_api):
        with allure.step("获取语言列表"):
            language_list = handle_api_call(system_api.get_language_list)

        with allure.step("更改语言"):
            set_language_list = [lang.get('key') for lang in language_list]
            set_language_list.append('auto')
            set_language = random.choice(set_language_list)
            handle_api_call(system_api.set_global_language, set_language)
            time.sleep(5)

        with allure.step("确认成功更改语言"):
            language = handle_api_call(system_api.get_global_language)
            assert language == set_language, f"更改语言失败，预期：{set_language}，实际：{language}"

        with allure.step("恢复语言为中文"):
            final_language = "zh-CN"
            handle_api_call(system_api.set_global_language, final_language)
            time.sleep(5)

    @allure.title("设置系统自动更新设置")
    def test_set_firmware_config(self, system_api):
        with allure.step("获取当前更新配置信息"):
            results = handle_api_call(system_api.get_firmware_config)
            auto_update = results.get('auto_update')
            enable_interval_time = results.get('custom_interval_time')
            interval_time = results.get('interval_time')

        with allure.step("更改配置信息"):
            set_auto_update = random.randint(0,2)
            set_enable_interval_time = random.choice([True, False])
            set_interval_time = random.randint(1,24)
            handle_api_call(system_api.set_firmware_config, auto_update=set_auto_update, custom_interval_time=set_enable_interval_time, interval_time=set_interval_time)
            time.sleep(5)

        with allure.step("确认成功更改配置信息"):
            new_results = handle_api_call(system_api.get_firmware_config)
            new_auto_update = new_results.get('auto_update')
            new_enable_interval_time = new_results.get('custom_interval_time')
            new_interval_time = new_results.get('interval_time')
            assert new_auto_update == set_auto_update, f"更改自动更新失败，预期：{set_auto_update}，实际：{new_auto_update}"
            assert new_enable_interval_time == set_enable_interval_time, f"更改启用间隔时间失败，预期：{set_enable_interval_time}，实际：{new_enable_interval_time}"
            assert new_interval_time == set_interval_time, f"更改间隔时间失败，预期：{set_interval_time}，实际：{new_interval_time}"

    @allure.title("更改系统更新设置")
    def test_set_firmware_config(self, system_api):
        with allure.step("获取当前更新配置信息"):
            results = handle_api_call(system_api.get_firmware_config)
            auto_update = results.get('auto_update')
            enable_interval_time = results.get('custom_interval_time')
            interval_time = results.get('interval_time')
            log.info(f"获取到更改前的配置信息为:更新策略:{auto_update},是否自定义检测更新：{enable_interval_time},自定义检测更新时间：{interval_time}")

        with allure.step("更改配置信息"):
            set_auto_update = random.randint(0, 2)
            set_enable_interval_time = random.choice([True, False])
            set_interval_time = random.randint(1, 24)
            handle_api_call(system_api.set_firmware_config, auto_update=set_auto_update,
                            custom_interval_time=set_enable_interval_time, interval_time=set_interval_time)
            time.sleep(5)

        with allure.step("确认成功更新配置"):
            new_results = handle_api_call(system_api.get_firmware_config)
            auto_update = new_results.get('auto_update')
            enable_interval_time = new_results.get('custom_interval_time')
            interval_time = new_results.get('interval_time')
            assert auto_update == set_auto_update, f"更改自动更新失败，预期：{set_auto_update}，实际：{auto_update}"
            assert enable_interval_time == set_enable_interval_time, f"更改启用间隔时间失败，预期：{set_enable_interval_time}，实际：{enable_interval_time}"
            if set_enable_interval_time == True:
                assert interval_time == set_interval_time, f"更改间隔时间失败，预期：{set_interval_time}，实际：{interval_time}"
